﻿using System.IO;
using System.Web;
using System.Web.Caching;
using System.Xml;
using System;

namespace GSMock.Resources
{
    /// <summary>
    ///   Search results manager.
    /// </summary>
    /// <remarks>
    ///   Handles the retrieval of the search results.
    /// </remarks>
    public class ResultsManager : FileBasedCacheManager
    {
        /// <summary>
        ///   Gets a set of results.
        /// </summary>
        /// <param name="results">The name of the results to retrieve.</param>
        /// <returns>
        ///   An XML document loaded with the results.
        /// </returns>
        public XmlDocument GetResults(string name)
        {
            XmlDocument resultsDoc = this.GetFromCache(name) as XmlDocument;

            if (resultsDoc == null)
            {
                var collection = Config.Configuration.GetConfig().Collections[name];

                if (collection != null)
                {
                    string filePath = this.HttpConext.Server.MapPath(collection.File);

                    // Get from disk.
                    resultsDoc = this.GetFromDisk(filePath);

                    // Add to cache for next time.
                    this.AddToCache(name, resultsDoc, filePath);
                }
                else
                {
                    throw new ApplicationException(
                        string.Format("No collection configured for name:{0}", name));
                }
            }

            return resultsDoc;
        }

        /// <summary>
        ///   Gets the results from disk.
        /// </summary>
        /// <param name="filePath">
        ///   The file path to the results file.
        /// </param>
        /// <returns>
        ///   An XML document loaded with the results.
        /// </returns>
        private XmlDocument GetFromDisk(string filePath)
        {
            if (System.IO.File.Exists(filePath))
            {
                XmlDocument resultsDoc = new XmlDocument();
                resultsDoc.Load(filePath);

                return resultsDoc;
            }
            else
            {
                throw new FileNotFoundException(
                    string.Format("Cannot find results file: {0}.", filePath));
            }
        }
    }
}
